from django.shortcuts import render

# Create your views here.
# GET /sms_code/(?<mobile>1[3-9]\d{9})/
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
import random
import logging
logger = logging.getLogger('django')


from meiduo_mall.apps.verifications import constans

class SmsCodeView(APIView):
    """
    生成随机6位短信验证码
    存在redis中key手机号  value是验证吗
    用骑牛云发送
    返回应答发送短信成功
    """
    def get(self, request , mobile):
        redis_conn = get_redis_connection("verify_codes")
        res = redis_conn.get("top_%s" % mobile)
        if res:
            return Response({'message':"发送短信过于频繁"}, status=status.HTTP_403_FORBIDDEN)



        sms_code = "%06d" % random.randint(0,999999)

        pl = redis_conn.pipeline()
        pl.setex(mobile, constans.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("top_%s" % mobile, constans.SMS_CODE_REDIS_EXPIRES, sms_code)

        pl.execute()
        sms_code_expires = constans.SMS_CODE_REDIS_EXPIRES // 60
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code, sms_code_expires)




        return Response({'message':'OK'})


